package edu.wuster.blog.controller;

/*
 * 用户controller类*/

import edu.wuster.blog.entity.LoginResponse;
import edu.wuster.blog.entity.Result;
import edu.wuster.blog.entity.User;
import edu.wuster.blog.entity.UserResetPassword;
import edu.wuster.blog.interf.AddGroup;
import edu.wuster.blog.interf.DefaultGroup;
import edu.wuster.blog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //登录
    @PostMapping("/login")
    public Result userLogin(@RequestBody User user) {
        log.info("用户（username：{}）正在登录", user.getUsername());
        LoginResponse loginResponse = userService.userLogin(user);
        log.info("登录成功");
        return Result.success(loginResponse);
    }

    //注销账号
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        log.info("用户(id：{})注销账号", id);
        userService.deleteUser(id);
        log.info("用户注销账号成功");
        return Result.success();
    }

    //用户修改密码接口
    @PutMapping("/password")
    public Result resetPassword(@RequestBody @Validated UserResetPassword userResetPassword) {
        userService.resetPassword(userResetPassword);
        return Result.success();
    }

    //用户修改个人信息接口
    @PutMapping
    public Result resetById(@RequestBody @Validated(DefaultGroup.class) User user) {
        userService.resetById(user);
        log.info("用户修改个人信息成功");
        return Result.success();
    }

    //用户查看个人信息接口
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        return Result.success(userService.selectById(id));
    }

    //用户忘记密码接口
    @PutMapping("/loss")
    public Result lossPassword(@RequestBody User user) {
        log.info("用户{}忘记密码", user.getUsername());
        if (userService.lossPassword(user))
            return Result.success();
        return Result.error("用户名或电话号码或身份证错误");
    }


    //用户注册接口
    @PostMapping("/register")
    public Result addUser(@RequestBody @Validated({AddGroup.class, DefaultGroup.class}) User user) {

        log.info("新增用户：{}", user.getUsername());

        userService.addUser(user);

        log.info("新增用户:{}，成功", user.getUsername());

        return Result.success();
    }
}
